<script setup>
  import { onMounted, ref } from 'vue'
  import { http } from '@/utils/http.js'
  import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'
  import { parseTime } from '@/utils/index.js'
  import { useUsercodeStore } from '@/store/usercode.js'

  const userCodeStore = useUsercodeStore()

  // 背包列表
  const bagGoods = ref([])
  const shopList = ref([])

  // const mergeList = ref([])
  const currentPage = ref(1)
  async function getBagList() {
    const res = await http.request({
      url: '/api/bag/bagShops',
      method: 'POST',
      data: {
        is_shop: 1,
        page: currentPage.value,
        limit: 10,
        compound: 0,
        type: 0,
        status: '1',
      },
    })
    // 计算多少天过期
    res.data.forEach((item) => {
      item.opened = false
    })
    shopList.value = [...shopList.value, ...res.data]
  }

  //折叠展开
  const goodsCurrentPage = ref(1)
  const shopId = ref('')
  async function getGoodsList() {
    const res = await http.request({
      url: '/api/bag/bagList',
      method: 'POST',
      data: {
        page: goodsCurrentPage.value,
        limit: 20,
        compound: 0,
        type: 0,
        launch: 2,
        status: 1,
        is_bidding: 0,
        rule_id: 0,
        shop_id: shopId.value,
      },
    })

    bagGoods.value = bagGoods.value.map((e) => {
      return Object.assign({}, e, {
        checked: false,
      })
    })
    res.data.forEach((item) => {
      item.checked = false
    })
    bagGoods.value = [...bagGoods.value, ...res.data]
  }

  const carddetailRef = ref()
  const clickItem = ref()
  function closeDetail() {
    carddetailRef.value.close('center')
  }
  function itemClick(item, index) {
    if (canChecked.value) {
      bagGoods.value[index].checked = !item.checked
      if (item.checked) {
        console.log('添加')
        deliveryList.value.push(item.goods_id)
      } else {
        deliveryList.value = deliveryList.value.filter(
          (e) => e !== item.goods_id
        )
      }
    } else {
      clickItem.value = item
      carddetailRef.value.open('center')
    }
  }
  //选择
  const deliveryList = ref([])
  const canChecked = ref(false)
  function canCheck() {
    canChecked.value = !canChecked.value
  }
  const allchecked = ref(false)
  function checkedAll() {
    if (!canChecked.value) {
      uni.showToast({
        icon: 'none',
        title: '请选点击选取',
      })
      return false
    }
    allchecked.value = !allchecked.value
    if (allchecked.value) {
      deliveryList.value = []
      bagGoods.value.forEach((item) => {
        item.checked = true
        deliveryList.value.push(item.goods_id)
      })
    } else {
      bagGoods.value.forEach((item) => {
        item.checked = false
      })
      deliveryList.value = []
    }
  }
  function openClick(item, index) {
    shopList.value = shopList.value.map((res) => {
      if (res.shop_id == item.shop_id) {
        if (!res.opened) {
          deliveryList.value = []
          bagGoods.value = []
          shopId.value = item.shop_id
          getGoodsList()
        }
        return Object.assign({}, res, {
          opened: !res.opened,
        })
      } else {
        return Object.assign({}, res, {
          opened: false,
        })
      }
    })
  }
  async function goOrder() {
    if (
      userCodeStore.usercode.token == '' ||
      userCodeStore.usercode.userId == ''
    ) {
      uni.utils.toast('为了让您有更好的体验，请先登录')
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/login/login`,
        })
      }, 2000)
      return
    }
    if (
      userCodeStore.usercode.isAddress == 0 &&
      userCodeStore.usercode.token != ''
    ) {
      uni.utils.toast('为了让您有更好的体验，请先完善物流信息')
      setTimeout(() => {
        uni.navigateTo({
          url: `/minePage/editaddress/index`,
        })
      }, 2000)
      return
    }
    if (deliveryList.value.length == 0) {
      uni.utils.toast('请选择奖品')
      return
    }
    const countMap = ref({})

    const arr = arrayToObject(deliveryList.value)

    const newarr = Object.entries(arr).map(([goods_id, num]) => ({
      goods_id,
      num,
    }))
    uni.navigateTo({
      url: `/mergePage/bagorder/index?info=${encodeURIComponent(
        JSON.stringify(newarr)
      )}&isShop=1`,
    })
    // const res = await http.request({
    //   url: '/api/bag/createShopOrderPage',
    //   method: 'POST',
    //   data: {
    //     goods_data: newarr,
    //     // idArr: detail.value,
    //     // address_id: addressid.value,
    //   },
    // })
    // if (res.st == 1) {
    //   const ress = await http.request({
    //     url: '/api/bag/createShopOrder',
    //     method: 'POST',
    //     data: {
    //       goods_data: newarr,
    //     },
    //   })
    //   if (res.st == 1) {
    //     uni.showToast({
    //       icon: 'none',
    //       title: '下单成功',
    //     })
    //   } else {
    //     uni.showToast({
    //       icon: 'none',
    //       title: res.msg,
    //     })
    //   }
    // } else {
    //   uni.showToast({
    //     icon: 'none',
    //     title: res.msg,
    //   })
    // }

    console.log(res)
  }
  function arrayToObject(arr) {
    return arr.reduce((acc, value) => {
      acc[value] = (acc[value] || 0) + 1
      return {
        ...acc,
      }
    }, {})
  }
  function getMore() {
    allchecked.value = false
    ++currentPage.value
    getBagList()
  }
  function getMoreGoods() {
    allchecked.value = false
    ++goodsCurrentPage.value
    getGoodsList()
  }

  onShareAppMessage(() => {
    return {
      title: '快来看看我的战利品',
      path: 'pages/bag/index',
    }
  })
  onShow(() => {
    currentPage.value = 1
    bagGoods.value = []
    shopList.value = []
    allchecked.value = false
    deliveryList.value = []
    getBagList()
  })
</script>

<template>
  <view class="bag-content">
    <view class="goods">
      <view class="">
        <scroll-view
          :scroll-y="true"
          class="scroll-shops"
          @scrolltolower="getMore"
        >
          <view style="padding: 0 20rpx; box-sizing: border-box">
            <view
              class="shopBox"
              v-for="(item, index) in shopList"
              :key="index"
            >
              <view class="shopItem" style="" @click="openClick(item, index)">
                <view style="display: flex; align-items: center">
                  <image
                    style="width: 60rpx"
                    src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/shopIcon.png"
                    mode="widthFix"
                  ></image>
                  <span style="margin-left: 6rpx">{{ item.shop_name }}</span>
                </view>
                <view style="color: #7948ea">{{
                  item.opened ? '折叠' : '展开'
                }}</view>
              </view>
              <scroll-view
                v-if="item.opened"
                :scroll-y="true"
                class="scroll-goods"
                @scrolltolower="getMoreGoods"
              >
                <view class="goods_box" style="">
                  <view
                    class="goods-item"
                    v-for="(obj, j) in bagGoods"
                    :key="j"
                    @click="itemClick(obj, j)"
                  >
                    <view class="goods-img">
                      <image
                        v-if="obj.rule_img"
                        :src="obj.rule_img"
                        mode="heightFix"
                        style="
                          position: absolute;
                          top: 0;
                          left: 0;
                          height: 44rpx;
                        "
                      ></image>
                      <image
                        class=""
                        :class="{
                          itemImg: true,
                          'goods-itemed': obj.checked ? true : false,
                        }"
                        :src="obj.img"
                        mode=""
                      ></image>
                      <image
                        class="checkImg"
                        v-if="obj.checked"
                        src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/checked.png"
                        mode=""
                      ></image>
                      <view class="item_num" v-if="obj.goods_num"
                        >{{ obj.goods_num }}{{ obj.true }}
                      </view>
                      <view class="presale" style="" v-if="obj.goods_type == 1">
                        预售
                      </view>
                    </view>
                  </view>
                  <view
                    class="goods-item"
                    v-for="(obj, j) in 8 - (bagGoods.length % 4)"
                    :key="'baggoods' + j"
                  >
                  </view>
                </view>
              </scroll-view>
            </view>
          </view>
        </scroll-view>
        <view class="bag-bottom">
          <view
            :class="{ 'all-select': true, 'all-selected': !allchecked }"
            @click="checkedAll"
            :checked="allchecked"
          >
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/all-select.png"
            ></image>
          </view>
          <view
            :class="{ 'check-all': true, 'all-selected': !canChecked }"
            @click="canCheck"
          >
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/check.png"
            ></image>
          </view>
          <view class="text-select">
            <text>已选:</text>
            <text style="color: #7948ea">{{ deliveryList.length }}</text>
          </view>
          <view class="shipment" @click="goOrder">
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/consult.png"
            ></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 说明弹出层 -->
    <uni-popup ref="carddetailRef" type="center">
      <view class="carddetail" v-if="clickItem">
        <image
          class="star"
          src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/star.png"
          mode="widthFix"
        ></image>
        <image
          @click="closeDetail"
          class="detailClose"
          src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/close.png"
          mode="widthFix"
        ></image>
        <view class="detail-title"> 详情 </view>
        <view class="detail-img">
          <image
            v-if="clickItem.rule_img"
            class="rule_img"
            :src="clickItem.rule_img"
            mode="heightFix"
          ></image>
          <image
            style="width: 100%"
            :src="clickItem.img"
            mode="widthFix"
          ></image>
        </view>
        <view class="carddetailInfo">
          <view class="top">
            {{ clickItem.goods_name }}
          </view>
          <view class="bottom">
            状态：{{ clickItem.goods_type == 1 ? '预售' : '现货' }}
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 说明弹出层 -->
  </view>
</template>

<style lang="scss" scoped>
  .scroll-goods {
    height: 50vh;
    .goods_box {
      border-top: 2rpx solid #c9c9c9;
      box-sizing: border-box;
      margin-top: 10rpx;
      // height: 72vh;
      display: flex;
      // align-items: center;
      flex-wrap: wrap;
      justify-content: space-around;
      padding: 20rpx;
      box-sizing: border-box;
    }
    .goods-itemed {
      filter: grayscale(60%);
    }
    .goods-item {
      display: flex;
      align-items: center;
      width: 128rpx;
      height: 188rpx;
      margin: 0 20rpx;
      // border-bottom: 1px solid #f5f5f5;
      box-sizing: border-box;
      margin-bottom: 20rpx;

      &:last-child {
        border: none;
      }
      .goods-img {
        position: relative;
        width: 128rpx;
        height: 180rpx;
        // height: 226rpx;
        border-radius: 8rpx;
        overflow: hidden;
        flex-shrink: 0;
        .checkImg {
          width: 76rpx;
          height: 76rpx;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-left: -38rpx;
          margin-top: -38rpx;
        }
        .itemImg {
          width: 128rpx;
          height: 180rpx;
        }
        .item_num {
          width: 40rpx;
          height: 30rpx;
          line-height: 30rpx;
          text-align: center;
          position: absolute;
          bottom: 0;
          right: 0;
          z-index: 1;
          border-radius: 6rpx;
          background: #fff;
          border: 2rpx solid rgba(121, 72, 234, 1);
          font-size: 20rpx;
          color: rgba(121, 72, 234, 1);
        }
        .presale {
          position: absolute;
          bottom: 0;
          left: 0;
          z-index: 1;
          width: 66rpx;
          height: 32rpx;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 0rpx 0rpx 8rpx 0rpx;
          font-size: 22rpx;
          color: #fff;
          line-height: 32rpx;
          text-align: center;
        }
      }
    }
  }
  .carddetail {
    width: 538rpx;
    height: 800rpx;
    border: 4rpx solid #740b00;
    background: #fff;
    border-radius: 24rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .detail-img {
      width: 366rpx;
      position: relative;
      .rule_img {
        height: 66rpx;
        position: absolute;
        top: 10rpx;
        left: 10rpx;
      }
    }
    .star {
      width: 80rpx;
      position: absolute;
      left: 6rpx;
      top: -56rpx;
    }
    .detailClose {
      width: 44rpx;
      position: absolute;
      right: 20rpx;
      top: -30rpx;
    }
    .detail-title {
      margin-top: 20rpx;
    }
    image {
      margin: 0 auto;
      margin-top: 20rpx;
    }
    .carddetailInfo {
      margin-top: 40rpx;
      width: 440rpx;
      height: 80rpx;
      border: 4rpx solid #740b00;
      border-radius: 8rpx;
      .top {
        width: 100%;
        height: 50rpx;
        text-align: center;
        line-height: 50rpx;
        color: #740b00;
        font-size: 26rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        padding: 0 10rpx;
        box-sizing: border-box;
      }
      .bottom {
        width: 100%;
        height: 30rpx;
        line-height: 30rpx;
        text-align: center;
        background: #b8a0e8;
        color: #ffffff;
        font-size: 18rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  .all-selected {
    filter: grayscale(70%);
  }
  .bag-content {
    padding-top: 40rpx;
    box-sizing: border-box;
    color: #3d3d3d;
    font-weight: 500;
    background: #fff;
    height: 100vh;
    .merge {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 156rpx;
      padding: 0rpx 20rpx 0 20rpx;
      box-sizing: border-box;
      .merge-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .title {
          font-size: 28rpx;
        }
        .go-merge {
          width: 178rpx;
          height: 48rpx;
          border-radius: 24rpx;
          background-color: #7863ff;
          font-size: 24rpx;
          text-align: center;
          line-height: 48rpx;
          color: #fff;
        }
      }
      .merge-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 18rpx;
        .content-item {
          width: 136rpx;
          height: 136rpx;
          border-radius: 10rpx;
          overflow: hidden;
        }
      }
    }

    .goods {
      .scroll-shops {
        height: 78vh;

        .shopBox {
          border-radius: 8rpx;
          align-items: center;

          padding: 20px 20rpx;
          box-sizing: border-box;
          margin-bottom: 20rpx;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
        }
        .shopItem {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 40rpx;
        }
      }
    }

    .bag-bottom {
      background-image: url(https://ojqn.wm2177.com/wechat_imgs/kapai-test/bag/bag-bottom.png);
      background-size: 100%;
      width: 100%;
      height: 218rpx;
      position: relative;
      .all-select {
        position: absolute;
        top: 92rpx;
        left: 40rpx;
        image {
          width: 140rpx;
          height: 72rpx;
        }
      }
      .check-all {
        position: absolute;
        top: 92rpx;
        left: 200rpx;
        image {
          width: 140rpx;
          height: 72rpx;
        }
      }
      .text-select {
        font-size: 24rpx;
        color: #000;
        position: absolute;
        top: 112rpx;
        right: 210rpx;
      }
      .shipment {
        position: absolute;
        top: 53rpx;
        right: 40rpx;
        image {
          width: 126rpx;
          height: 126rpx;
        }
      }
    }

    ::v-deep .uni-popup__wrapper-box {
      width: 100%;
      padding: 0;
      display: flex;
      justify-content: center;
    }
  }
</style>
